Page({
  data: {
    // 搜索关键词
    searchKeyword: '',
    
    // 选中的分类
    selectedCategory: 'all',
    
    // 商品分类
    categories: [
      { id: 'all', name: '全部', icon: '🎆' },
      { id: 'hot-service', name: '热门服务', icon: '🔥' },
      { id: 'points', name: '积分兑换', icon: '🏆' },
      { id: 'yiwu-goods', name: '义乌好物', icon: '🎁' }
    ],
    
    // 商品列表
    goodsList: [
      // 翻译服务
      {
        id: 1,
        name: '专业翻译服务',
        price: '￥150/小时',
        image: 'cloud://cloud1-5gn2jipsaa21f49d.636c-cloud1-5gn2jipsaa21f49d-1381622514/services_multi-language.gif',
        category: 'hot-service',
        type: 'service',
        description: '商务、医疗、法律等专业翻译',
        rating: 4.8,
        orders: 156,
        tags: ['在线服务', '专业认证'],
        seller: '专业翻译工作室',
        isHot: true
      },
      {
        id: 2,
        name: '法律咨询券',
        price: '￥200',
        originalPrice: '￥300',
        image: 'cloud://cloud1-5gn2jipsaa21f49d.636c-cloud1-5gn2jipsaa21f49d-1381622514/123123.jpg',
        category: 'hot-service',
        type: 'service',
        description: '合作律所一对一咨询服务',
        rating: 4.9,
        orders: 89,
        tags: ['限时优惠', '一对一咨询'],
        seller: '义乌律法事务所',
        isDiscount: true
      },
      {
        id: 3,
        name: '政务代办服务',
        price: '￥80',
        image: '/images/default-goods-image.png',
        category: 'hot-service',
        type: 'service',
        description: '暂住证、居住证代办服务',
        rating: 4.7,
        orders: 234,
        tags: ['高效办理', '专业代办'],
        seller: '便民服务中心'
      },
      
      // 积分兑换商品
      {
        id: 4,
        name: '鸡毛换糖帆布包',
        price: '500积分',
        image: '/images/default-goods-image.png',
        category: 'points',
        type: 'points',
        description: '义乌特色文创产品',
        stock: 28,
        tags: ['文创精品', '限量版'],
        seller: '义乌文创'
      },
      {
        id: 5,
        name: '咖啡馆优惠券',
        price: '300积分',
        image: '/images/default-goods-image.png',
        category: 'points',
        type: 'points',
        description: '合作咖啡馆满减优惠券',
        stock: 50,
        tags: ['美食优惠', '限时兑换'],
        seller: '清新咖啡'
      },
      {
        id: 6,
        name: '线下活动优先权',
        price: '800积分',
        image: '/images/default-goods-image.png',
        category: 'points',
        type: 'points',
        description: '热门线下活动优先参与权',
        stock: 15,
        tags: ['精彩活动', '优先参与'],
        seller: '活动主办方',
        isRare: true
      },
      
      // 义乌好物
      {
        id: 7,
        name: '义乌精美工艺品',
        price: '参考价￥280',
        image: '/images/default-goods-image.png',
        category: 'yiwu-goods',
        type: 'showcase',
        description: '非物质文化遗产工艺品',
        location: '义乌国际商贸城 A区',
        contact: '张师僅 138****1234',
        tags: ['非物质文化遗产', '手工制作'],
        seller: '义乌工艺坊'
      },
      {
        id: 8,
        name: '优质小商品样品',
        price: '批发价格面议',
        image: '/images/default-goods-image.png',
        category: 'yiwu-goods',
        type: 'showcase',
        description: '义乌精品小商品展示',
        location: '义乌国际商贸城 B区',
        contact: '李经理 139****5678',
        tags: ['优质货源', '批发优惠'],
        seller: '义乌贸易公司'
      }
    ],
    
    // 过滤后的商品列表
    filteredGoods: [],
    
    // 是否显示返回顶部按钮
    showBackTop: false,
    
    // 页面状态
    loading: false,
    
    // 用户积分（模拟数据）
    userPoints: 1250
  },

  onLoad() {
    console.log('商城页面加载');
    this.initGoodsList();
  },

  onShow() {
    // 更新用户积分
    this.getUserPoints();
    
    // 更新 TabBar 选中状态
    this.updateTabBarSelected();
  },

  // 初始化商品列表
  initGoodsList() {
    this.setData({
      loading: true
    });
    
    // 模拟加载延迟
    setTimeout(() => {
      this.filterGoods();
      this.setData({
        loading: false
      });
    }, 500);
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 执行搜索
  onSearch() {
    this.filterGoods();
    wx.showToast({
      title: `搜索“${this.data.searchKeyword}”`,
      icon: 'none',
      duration: 1500
    });
  },

  // 分类选择
  onCategoryChange(e) {
    const categoryId = e.currentTarget.dataset.id;
    this.setData({
      selectedCategory: categoryId
    });
    this.filterGoods();
  },

  // 过滤商品
  filterGoods() {
    const { goodsList, selectedCategory, searchKeyword } = this.data;
    let filtered = goodsList;

    // 按分类过滤
    if (selectedCategory !== 'all') {
      filtered = filtered.filter(item => item.category === selectedCategory);
    }

    // 按搜索关键词过滤
    if (searchKeyword.trim()) {
      const keyword = searchKeyword.toLowerCase();
      filtered = filtered.filter(item => 
        item.name.toLowerCase().includes(keyword) ||
        item.description.toLowerCase().includes(keyword) ||
        item.seller.toLowerCase().includes(keyword)
      );
    }

    this.setData({
      filteredGoods: filtered
    });
  },

  // 商品点击
  onGoodsClick(e) {
    const goods = e.currentTarget.dataset.goods;
    
    if (goods.type === 'service') {
      // 服务类商品
      this.handleServiceClick(goods);
    } else if (goods.type === 'points') {
      // 积分兑换
      this.handlePointsClick(goods);
    } else if (goods.type === 'showcase') {
      // 展示类商品
      this.handleShowcaseClick(goods);
    }
  },

  // 处理服务类点击
  handleServiceClick(goods) {
    wx.showModal({
      title: '预约服务',
      content: `您要预约「${goods.name}」服务吗？`,
      confirmText: '立即预约',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '预约中...',
            mask: true
          });
          
          setTimeout(() => {
            wx.hideLoading();
            wx.showToast({
              title: '预约成功！',
              icon: 'success'
            });
          }, 1500);
        }
      }
    });
  },

  // 处理积分兑换点击
  handlePointsClick(goods) {
    const requiredPoints = parseInt(goods.price.replace('积分', ''));
    
    if (this.data.userPoints < requiredPoints) {
      wx.showToast({
        title: '积分不足，多参与活动获取积分吧！',
        icon: 'none',
        duration: 2500
      });
      return;
    }
    
    wx.showModal({
      title: '积分兑换',
      content: `确认花费 ${requiredPoints} 积分兑换「${goods.name}」吗？`,
      confirmText: '立即兑换',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '兑换中...',
            mask: true
          });
          
          setTimeout(() => {
            wx.hideLoading();
            this.setData({
              userPoints: this.data.userPoints - requiredPoints
            });
            
            wx.showToast({
              title: '兑换成功！',
              icon: 'success'
            });
          }, 1500);
        }
      }
    });
  },

  // 处理展示类点击
  handleShowcaseClick(goods) {
    wx.showModal({
      title: goods.name,
      content: `地址：${goods.location}\n联系方式：${goods.contact}\n\n描述：${goods.description}`,
      confirmText: '复制联系方式',
      success: (res) => {
        if (res.confirm) {
          wx.setClipboardData({
            data: goods.contact,
            success: () => {
              wx.showToast({
                title: '联系方式已复制',
                icon: 'success'
              });
            }
          });
        }
      }
    });
  },

  // 页面滚动监听
  onPageScroll(e) {
    const scrollTop = e.scrollTop;
    const showBackTop = scrollTop > 500;
    
    if (showBackTop !== this.data.showBackTop) {
      this.setData({
        showBackTop
      });
    }
  },

  // 返回顶部
  backToTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 500
    });
  },

  // 获取用户积分
  getUserPoints() {
    // 这里可以从服务器获取用户积分
    // 暂时使用模拟数据
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.initGoodsList();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  // 上拉加载更多
  onReachBottom() {
    wx.showToast({
      title: '没有更多商品了',
      icon: 'none'
    });
  },

  // 更新 TabBar 选中状态
  updateTabBarSelected() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().updateSelectedIndex();
    }
  }
});